package com.hra.logger;

import android.app.AlertDialog;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ListView;
import android.widget.Toast;

import androidx.appcompat.app.AppCompatActivity;

import com.hra.logger.utils.Utils;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

public class LogCleanerActivity extends AppCompatActivity {

    private ArrayAdapter<String> adapter;
    private final List<File> currentFiles = new ArrayList<>();
    private final List<String> currentFileNames = new ArrayList<>();
    private AlertDialog progressDialog;
    private File rootDir;
    private File currentDir;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_log_cleaner);

        ListView logListView = findViewById(R.id.log_list_view);
        Button clearButton = findViewById(R.id.clear_button);

        rootDir = new File(Utils.LOG_PATH);
        currentDir = rootDir;

        scanCurrentDir();

        adapter = new ArrayAdapter<>(this, android.R.layout.simple_list_item_1, currentFileNames);
        logListView.setAdapter(adapter);

        // Click on the list item. Determine whether it is a folder or a file
        logListView.setOnItemClickListener((parent, view, position, id) -> {
            File clickedFile = currentFiles.get(position);
            if (clickedFile.isDirectory()) {
                // Enter folder
                currentDir = clickedFile;
                scanCurrentDir();
                adapter.notifyDataSetChanged();
            }
        });

        // Long press the listener, long press the folder to pop up a confirmation box for deleting the entire folder
        logListView.setOnItemLongClickListener((parent, view, position, id) -> {
            File clickedFile = currentFiles.get(position);
            if (clickedFile.isDirectory()) {
                showDeleteFolderConfirmDialog(clickedFile);
            } else {
                // A confirmation box pops up here to delete the file separately
                showDeleteFileConfirmDialog(clickedFile);
            }
            return true;
        });

        clearButton.setOnClickListener(v -> showClearConfirmDialog());
    }

    private void scanCurrentDir() {
        currentFiles.clear();
        currentFileNames.clear();

        if (currentDir.exists() && currentDir.isDirectory()) {
            File[] files = currentDir.listFiles();
            if (files != null) {
                for (File f : files) {
                    currentFiles.add(f);
                    currentFileNames.add(f.getName() + (f.isDirectory() ? "/" : ""));
                }
            }
        }
    }

    private void showClearConfirmDialog() {
        if (currentFiles.isEmpty()) {
            Toast.makeText(this, R.string.no_logs, Toast.LENGTH_SHORT).show();
            return;
        }

        new AlertDialog.Builder(this)
                .setTitle(R.string.delete_sure_title)
                .setMessage(R.string.delete_current_sure_msg)
                .setPositiveButton(android.R.string.ok, (dialog, which) -> {
                    deleteFilesAsync(new ArrayList<>(currentFiles));
                })
                .setNegativeButton(android.R.string.cancel, null)
                .show();
    }

    private void deleteFilesAsync(List<File> filesToDelete) {
        View dialogView = LayoutInflater.from(this).inflate(R.layout.dialog_delete_progress, null);
        progressDialog = new AlertDialog.Builder(this)
                .setTitle(R.string.delete_logs)
                .setView(dialogView)
                .setCancelable(false)
                .create();
        progressDialog.show();

        new Thread(() -> {
            int deletedCount = 0;
            for (File file : filesToDelete) {
                if (file.isDirectory()) {
                    deletedCount += deleteRecursively(file);
                } else if (file.delete()) {
                    deletedCount++;
                } else {
                    runOnUiThread(() -> {
                        Toast.makeText(this, R.string.delete_failed, Toast.LENGTH_SHORT).show();
                    });
                }
            }
            int finalDeletedCount = deletedCount;
            runOnUiThread(() -> {
                if (progressDialog != null && progressDialog.isShowing()) {
                    progressDialog.dismiss();
                }
                Toast.makeText(this, getString(R.string.delete_sure_result, finalDeletedCount), Toast.LENGTH_SHORT).show();
                scanCurrentDir();
                adapter.notifyDataSetChanged();
            });
        }).start();
    }

    private int deleteRecursively(File file) {
        int count = 0;
        if (file.isDirectory()) {
            File[] children = file.listFiles();
            if (children != null) {
                for (File child : children) {
                    count += deleteRecursively(child);
                }
            }
        }
        if (file.delete()) count++;
        return count;
    }

    private void showDeleteFileConfirmDialog(File file) {
        new AlertDialog.Builder(this)
                .setTitle(R.string.delete_sure_title)
                .setMessage(getString(R.string.delete_file_sure_msg, file.getName()))
                .setPositiveButton(android.R.string.ok, (dialog, which) -> {
                    List<File> filesToDelete = new ArrayList<>();
                    filesToDelete.add(file);
                    deleteFilesAsync(filesToDelete);
                })
                .setNegativeButton(android.R.string.cancel, null)
                .show();
    }

    private void showDeleteFolderConfirmDialog(File folder) {
        new AlertDialog.Builder(this)
                .setTitle(R.string.delete_sure_title)
                .setMessage(getString(R.string.delete_sure_msg, folder.getName()))
                .setPositiveButton(android.R.string.ok, (dialog, which) -> {
                    List<File> filesToDelete = new ArrayList<>();
                    filesToDelete.add(folder);
                    deleteFilesAsync(filesToDelete);
                })
                .setNegativeButton(android.R.string.cancel, null)
                .show();
    }

    @Override
    public void onBackPressed() {
        if (!currentDir.equals(rootDir)) {
            currentDir = currentDir.getParentFile();
            scanCurrentDir();
            adapter.notifyDataSetChanged();
        } else {
            super.onBackPressed();
        }
    }
}
